import { defineComponent, ref, onMounted, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { Row, Spin, Image, Progress } from "ant-design-vue";
import { course as Course } from "@/api";
import { useSystemStore } from "@/stores";
import mediaIcon from "@/assets/images/commen/icon-medal.png";
import { HourComponent } from "./components/HourComponent";
import { Empty } from "@/components";
import iconRoute from "@/assets/images/commen/icon-route.png";
import defaultThumb1 from "@/assets/thumb/thumb1.png";
import defaultThumb2 from "@/assets/thumb/thumb2.png";
import defaultThumb3 from "@/assets/thumb/thumb3.png";
import styles from "./course/index.module.scss";

type TabModel = {
  key: number;
  label: string;
};

type AttachModel = {
  id: number;
  course_id: number;
  rid: number;
  sort: number;
  title: string;
  type: string;
  url?: string;
};

type HoursModel = {
  [key: number]: HourModel[];
};

type ChapterModel = {
  course_id: number;
  created_at: string;
  id: number;
  name: string;
  sort: number;
  updated_at: string;
};

type LearnHourRecordsModel = {
  [key: number]: HourRecordModel;
};

export default defineComponent({
  name: "CoursePage",
  setup() {
    const router = useRouter();
    const route = useRoute();
    const params = route.params;
    const systemStore = useSystemStore();

    const loading = ref<boolean>(true);
    const course = ref<CourseModel | null>(null);
    const chapters = ref<ChapterModel[]>([]);
    const hours = ref<HoursModel>({});
    const learnRecord = ref<CourseRecordModel | null>(null);
    const learnHourRecord = ref<LearnHourRecordsModel>({});
    const tabKey = ref(Number(route.query.tab || 1));
    const attachments = ref<AttachModel[]>([]);
    const resourceUrl = ref<ResourceUrlModel>({});
    const items = ref<TabModel[]>([]);

    onMounted(() => {
      getDetail();
    });

    const getDetail = () => {
      loading.value = true;
      Course.detail(Number(params.courseId))
        .then((res: any) => {
          document.title = res.data.course.title;
          course.value = res.data.course;
          chapters.value = res.data.chapters;
          hours.value = res.data.hours;
          resourceUrl.value = res.data.resource_url;
          if (res.data.learn_record) {
            learnRecord.value = res.data.learn_record;
          }
          if (res.data.learn_hour_records) {
            learnHourRecord.value = res.data.learn_hour_records;
          }
          let arr: AttachModel[] = res.data.attachments;
          let tabs: TabModel[] = [
            {
              key: 1,
              label: `课程目录`,
            },
          ];
          if (arr.length > 0) {
            tabs.push({
              key: 2,
              label: `课程附件`,
            });
            attachments.value = arr;
          }
          items.value = tabs;

          loading.value = false;
        })
        .catch((e) => {
          loading.value = false;
        });
    };

    const onChange = (key: number) => {
      tabKey.value = key;
      router.push(`/course/${params.courseId}?tab=${key}`);
    };

    const downLoadFile = (cid: number, id: number, rid: number, fileName: string, type: string) => {
      Course.downloadAttachment(cid, id).then((res: any) => {
        if (type === "TXT") {
          fetch(res.data.resource_url[rid])
            .then((response) => response.blob())
            .then((blob) => {
              const n_url = URL.createObjectURL(blob);
              const a = document.createElement("a");
              a.style.display = "none";
              a.href = n_url;
              a.download = fileName; // 设置下载的文件名
              document.body.appendChild(a);
              a.click(); // 触发点击事件
              // 释放 URL 对象
              URL.revokeObjectURL(n_url);
              document.body.removeChild(a);
            })
            .catch((error) => {
              console.error("下载文件时出错:", error);
            });
        } else {
          window.open(res.data.resource_url[rid]);
        }
      });
    };

    const getThumbSrc = (thumb: number) => {
      if (thumb === -1) return defaultThumb1;
      if (thumb === -2) return defaultThumb2;
      if (thumb === -3) return defaultThumb3;
      return resourceUrl.value[thumb];
    };

    const getProgressPercent = () => {
      if (!learnRecord.value || JSON.stringify(learnRecord.value) === "{}") {
        if (JSON.stringify(learnHourRecord.value) === "{}") {
          return 0;
        }
        return 1;
      }
      if (JSON.stringify(learnRecord.value) !== "{}" && JSON.stringify(learnHourRecord.value) !== "{}") {
        return Math.floor(learnRecord.value.progress / 100);
      }
      return 0;
    };

    return () => (
      <div class="container">
        {loading.value && (
          <Row
            style={{
              width: 1200,
              margin: "0 auto",
              paddingTop: 14,
              minHeight: 301,
            }}
          >
            <div class="float-left d-j-flex mt-50">
              <Spin size="large" />
            </div>
          </Row>
        )}
        {!loading.value && (
          <>
            <div class={styles["top-cont"]}>
              <div class="j-b-flex">
                <div class="d-flex">
                  {course.value ? <Image width={120} height={90} style={{ borderRadius: 10 }} preview={false} src={getThumbSrc(course.value.thumb)} /> : null}
                  <div class={styles["info"]}>
                    <div class={styles["title"]}>{course.value?.title}</div>
                    <div class={styles["status"]}>
                      {course.value?.is_required === 1 && <div class={styles["type"]}>必修课</div>}
                      {course.value?.is_required === 0 && <div class={styles["active-type"]}>选修课</div>}
                      {learnRecord.value && learnRecord.value.progress / 100 >= 100 && (
                        <div class={styles["success"]}>
                          <Image width={24} height={24} src={mediaIcon} preview={false} />
                          <span class="ml-8">恭喜你学完此课程!</span>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
                <Progress type="circle" strokeColor="#FF4D4F" trailColor="#F6F6F6" size={90} strokeWidth={8} percent={getProgressPercent()} format={(percent) => `${percent}%`} />
              </div>
              {course.value?.short_desc && <div class={styles["desc"]}>{course.value.short_desc}</div>}
            </div>
            <div class={styles["tabs"]}>
              {items.value.map((item: any) => (
                <div
                  key={item.key}
                  class={item.key === tabKey.value ? styles["tab-active-item"] : styles["tab-item"]}
                  onClick={() => {
                    onChange(item.key);
                  }}
                >
                  <div class={styles["tit"]}>{item.label}</div>
                  {item.key === tabKey.value && <Image class={styles["banner"]} width={40} height={8} preview={false} src={iconRoute} style={{ marginTop: -16 }} />}
                </div>
              ))}
            </div>
            {tabKey.value === 1 && (
              <div class={styles["chapters-hours-cont"]}>
                {chapters.value.length === 0 && JSON.stringify(hours.value) === "{}" && <Empty />}
                {chapters.value.length === 0 && JSON.stringify(hours.value) !== "{}" && (
                  <div class={styles["hours-list-box"]}>
                    {hours.value[0].map((item: any, index: number) => (
                      <div key={item.id} class={styles["hours-it"]}>
                        {learnHourRecord.value[item.id] && (
                          <HourComponent
                            id={item.id}
                            cid={item.course_id}
                            title={item.title}
                            record={learnHourRecord.value[item.id]}
                            duration={item.duration}
                            progress={(learnHourRecord.value[item.id].finished_duration * 100) / learnHourRecord.value[item.id].total_duration}
                          />
                        )}
                        {!learnHourRecord.value[item.id] && <HourComponent id={item.id} cid={item.course_id} title={item.title} record={null} duration={item.duration} progress={0} />}
                      </div>
                    ))}
                  </div>
                )}
                {chapters.value.length > 0 && JSON.stringify(hours.value) !== "{}" && (
                  <div class={styles["hours-list-box"]}>
                    {chapters.value.map((item: any, index: number) => (
                      <div key={item.id} class={styles["chapter-it"]}>
                        <div class={styles["chapter-name"]}>{item.name}</div>
                        {hours.value[item.id] &&
                          hours.value[item.id].map((it: any, int: number) => (
                            <div key={it.id} class={styles["hours-it"]}>
                              {learnHourRecord.value[it.id] && (
                                <HourComponent
                                  id={it.id}
                                  cid={item.course_id}
                                  title={it.title}
                                  record={learnHourRecord.value[it.id]}
                                  duration={it.duration}
                                  progress={(learnHourRecord.value[it.id].finished_duration * 100) / learnHourRecord.value[it.id].total_duration}
                                />
                              )}
                              {!learnHourRecord.value[it.id] && <HourComponent id={it.id} cid={item.course_id} title={it.title} record={null} duration={it.duration} progress={0} />}
                            </div>
                          ))}
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )}
            {tabKey.value === 2 && (
              <div class={styles["attachments-cont"]}>
                {attachments.value.map((item: any, index: number) => (
                  <div key={index} class={styles["attachments-item"]}>
                    <div class={styles["left-cont"]}>
                      <i
                        class="iconfont icon-icon-file"
                        style={{
                          fontSize: 16,
                          color: "rgba(0,0,0,0.3)",
                          marginRight: 10,
                        }}
                      />
                      <span class={styles["title"]}>
                        {item.title}.{item.ext}
                      </span>
                    </div>
                    <div class={styles["download"]} onClick={() => downLoadFile(item.course_id, item.id, item.rid, `${item.title}.${item.ext}`, item.type)}>
                      下载
                    </div>
                  </div>
                ))}
              </div>
            )}
          </>
        )}
      </div>
    );
  },
});
